<template>
  {{ devtitle.subTitel }} {{ devtitle.subType }}

  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="key" label="Key" width="200px" />
    <el-table-column prop="val" label="Val" width="200px" />
  </el-table>
</template>

<script setup>
import { toRefs, onMounted, ref, reactive, onBeforeUnmount } from 'vue';
import { InfluxDB, flux } from '@influxdata/influxdb-client'
const url = "http://localhost:8086";
const token = 'aGlLIdBZktDg7r9OWrliaxRaR5FnqxwXYm6Oc7qZi9ntGml91u-GY61XDoBT0iqSVHxFfPdunWYk9PqTUYDWAw=='
const org = 'family'
const bucket = 'iot'
const client = new InfluxDB({ url: url, token: token })
const timev = 2
const queryApi = client.getQueryApi(org)


const props = defineProps({
  title: {
    type: Object
  }
})
const devtitle = toRefs(props.title);

const devname = ref(devtitle.subTitel)

const queryb = flux`from(bucket: "${bucket}") 
  |> range(start: -${timev}d)
  |> filter(fn: (r) => r._measurement == "${devname.value}")
  |> last()`

let  tableData = reactive([
])

const data = reactive([])
const timeProc = () => {
  queryApi.queryRows(queryb, {
    next(row, tableMeta) {
      const o = tableMeta.toObject(row)
      // console.log(`${o._time} ${o._measurement}: ${o._field}=${o._value}`)
      if (!data[o._measurement]) data[o._measurement] = {}
      data[o._measurement][o._field] = o._value
      // data.push(o._measurement)
    },
    error(error) {
      console.error(error)
      console.log('Finished ERROR')
    },
    complete() {
      console.log('Finished SUCCESS')
      Object.keys(data).forEach((key) => {
        // console.log(key)
        tableData.length = 0
        Object.keys(data[key]).forEach((key1) => {
         
          tableData.push({
            key: `${key1}`,
            val: data[key][key1],
          });
        });
        // tableData.push({key:key, val:data[key]})
      })
    },
  })
}
let timer = Object
onMounted(() => {
  timer = setInterval(timeProc, 3000);
},
)
onBeforeUnmount(() => {
  clearInterval(timer);
  console.log('unmount... ');
})
</script>

<style scoped></style>